import { Image, InfiniteScroll, List } from "antd-mobile";
import { useEffect, useState } from "react";
import { articleResDataInt, getArticlesData } from "@/apis/home";
import { useNavigate } from "react-router-dom";

type propsType = {
  channelId: number;
};

function HomeList(props: propsType) {
  const { channelId } = props;
  const [articleRes, setArticleRes] = useState<articleResDataInt>();
  // 是否还有更多数据
  const [hasMore, setHasMore] = useState(true);

  useEffect(() => {
    const getArticlesFun = async () => {
      try {
        const res = await getArticlesData({
          channel_id: channelId,
          timestamp: new Date().getTime() + "",
        });

        setArticleRes({
          pre_timestamp: res.data.pre_timestamp,
          results: res.data.results,
        });
      } catch (error) {
        throw new Error("fetch list error");
      }
    };
    getArticlesFun();
  }, [channelId]);
  // 上拉加载函数
  const loadMore = async () => {
    try {
      if (!articleRes) return;
      const res = await getArticlesData({
        channel_id: channelId,
        timestamp: articleRes.pre_timestamp,
      });
      setArticleRes({
        pre_timestamp: res.data.pre_timestamp,
        results: [...articleRes.results, ...res.data.results],
      });
      if (res.data.results?.length === 0) {
        setHasMore(false);
      }
    } catch (error) {
      throw new Error("fetch list error");
    }
  };
  const Navigate = useNavigate();
  const clickFun = (art_id: string) => {
    Navigate(`/detail?art_id=${art_id}`);
  };
  if (!articleRes) {
    return <div>玩命加载中...</div>;
  }

  return (
    <>
      <List>
        {articleRes?.results?.map((item) => (
          <List.Item
            key={item.art_id}
            prefix={
              <Image
                src={item.cover?.images?.[0]}
                style={{ borderRadius: 20 }}
                fit="cover"
                width={40}
                height={40}
              />
            }
            description={item.pubdate}
            onClick={() => clickFun(item.art_id)}
          >
            {item.title}
          </List.Item>
        ))}
      </List>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={10} />
    </>
  );
}
export { HomeList };
